package com.fly.show.users.service.impl;

import java.util.Date;
import java.util.stream.IntStream;

import javax.annotation.PostConstruct;

import org.apache.commons.lang3.RandomUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import com.fly.show.users.entity.User;
import com.fly.show.users.repository.UserRepository;
import com.fly.show.users.service.UserService;

import lombok.extern.slf4j.Slf4j;

@Slf4j
@Service
public class UserServiceImpl implements UserService
{
    @Autowired
    UserRepository userRepository;
    
    private Long sequence = 1L;
    
    /**
     * 初始化
     * 
     * @see [类、类#方法、类#成员]
     */
    @PostConstruct
    public void init()
    {
        Date now = new Date();
        IntStream.range(0, 20).forEach(i -> {
            userRepository.save(new User().setUserId(sequence).setUserName("user_" + sequence).setAge(RandomUtils.nextInt(10, 40)).setDesc("This is a user " + sequence).setCreateTime(now));
            sequence++;
        });
    }
    
    /**
     * 新增/根据id更新
     * 
     * @param user
     * @see [类、类#方法、类#成员]
     */
    @Override
    public void saveOrUpdate(User user)
    {
        if (user.getUserId() == null)
        {
            user.setUserId(sequence++);
        }
        userRepository.save(user);
    }
    
    @Override
    public void delete(Long userId)
    {
        log.info("delete user id = {}", userId);
        userRepository.deleteById(userId);
    }
    
    @Override
    public User get(Long userId)
    {
        log.info("get user id = {}", userId);
        if (!userRepository.existsById(userId))
        {
            return null;
        }
        return userRepository.findById(userId).get();
    }
    
    @Override
    public Page<User> page()
    {
        Pageable pageable = PageRequest.of(0, 10);
        return userRepository.findAll(pageable);
    }
    
    @Override
    public Page<User> page(int pageNo)
    {
        log.info("pageNo = {} ", pageNo);
        Pageable pageable = PageRequest.of(pageNo, 10);
        return userRepository.findAll(pageable);
    }
}
